<template>
  <div style="min-height: 450px">
    <el-table :data="state.allRoles" ref="userRoleTable" tooltip-effect="dark" border style="width: 100%" @selection-change="handleSelectionChange" >
      <el-table-column type="selection" width="55"></el-table-column>
      <el-table-column label="角色名称" prop="roleName"></el-table-column>
    </el-table>
    <div class="mt_5 tac">
      <el-button type="primary" size="default" @click="saveUserRole">确定</el-button>
    </div>
  </div>
</template>

<script setup name="userRole">
import request from '/@/utils/request';
import { ElMessage } from 'element-plus';
import {reactive, ref, onMounted, defineProps, defineEmits, nextTick} from "vue";

const userRoleTable = ref(null)
let props = defineProps({
  entityId : {type : Number, default: 0}
})
const state = reactive({
  allRoles :[],
  selectRoles:[],
})

const handleSelectionChange = (selectRows)=>{
  state.selectRoles = selectRows
}
const saveUserRole = ()=>{
  let userRoles = [];
  state.selectRoles.forEach((r)=>{
    userRoles.push(r.id)
  })
  request({
    url: '/sys/useradmin/saveuserrole',
    data: {userId : props.entityId, userRoles:userRoles}
  }).then(res=>{
    if(res.code === '200'){
      ElMessage.success(res.msg)
    }
  })
}
const loadUserRole = ()=>{
  request({
    url: '/sys/useradmin/listuserrole',
    data: {userId : props.entityId}
  }).then(res => {
    const { data } = res
    state.allRoles = data.allRoles
    nextTick(()=>{
      state.allRoles.forEach((item)=>{
        if(data.userRoles.filter((u)=> u.id === item.id).length > 0){
          userRoleTable && userRoleTable.value.toggleRowSelection(item, true)
        }
      })
    })
  })
}

onMounted(()=>{
  loadUserRole();
})

</script>

<style scoped>

</style>
